/* eslint-disable max-lines */
/* eslint-disable react/jsx-closing-tag-location */
import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Dialog, Form, ResponsiveGrid, Message, Tab, Icon, Notification, Input, Switch, Checkbox, NumberPicker } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid, TitleGrid, column, orderModel } from '../../stores/definitions_refund';
import { observer } from 'mobx-react-lite';
import { observable, toJS } from 'mobx';
import moment from 'moment';
import { uniqueId } from 'lodash';
import AttachmentForm from '../AttachmentForm';
import TauTable from '@/components/TauTable';
import UploadPanel from '@/components/UploadPanel';
import { verifyAccount, currentEditAccount, verifyAccountTotal, refundCaution, currentIsEdit, currentIsEditPS, isRefundPrice, computePrice } from '../../stores/method';
import RefundRule from './RefundRule';

const FromItem = Form.Item;
const { Cell } = ResponsiveGrid;

const tabItems = [
  { key: '0', label: t`退款` },
  { key: '1', label: t`追加退款` },
];

const abTabItems = [
  { key: '0', label: t`A段` },
  { key: '1', label: t`B段` },
];

const tableId = uniqueId('tauTable-');

function OrderRefund({ order, modal, onSubmit, onCancel, isEdit, onEdit }) {
  const { ccOrderStore: store } = useStore();
  const [accountsA, setAccountsA] = useState([]);
  const [accountsB, setAccountsB] = useState([]);
  const [accountSupplement, setAccountSupplement] = useState([]);
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [orderRefund] = useState(() => observable({}));
  const [tabIndex, setTabIndex] = useState('0');
  const [abIndex, setABIndex] = useState('');
  const [AB, setAB] = useState(false);
  const [enableProfitShare, setEnableProfitShare] = useState(false); // 订单是否已经开启分账
  const [cancelOrder, setCancelOrder] = useState(false); // 订单是否已经开启分账
  const [refundAmount, setRefundAmount] = useState(); // a段分账方成本
  const [refundAmountB, setRefundAmountB] = useState(); // b段分账方成本
  const [costTotalPrice, setCostTotalPrice] = useState(0); // a段订单成本

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  // 是否是编辑
  const edit = isEdit === 1;

  const tabContentA = {
    0: [edit ? 'orderInfo.orderPrice' : 'price', 'actualPrice', 'discountPrice', edit ? 'orderInfo.orderState' : 'ccOrder.orderStatus',
      'cancelOrder', 'enableProfitShare', 'refundPrice', 'serviceCharge', 'cancelTime', 'distanceTime', 'cancelRemark',
    ],
    1: [edit ? 'orderInfo.orderPrice' : 'price', 'actualPrice', 'discountPrice', edit ? 'orderInfo.orderState' : 'ccOrder.orderStatus', 'refundPrice',
      'cancelRemark'],
  };

  const tabContentB = {
    0: [edit ? 'orderInfo.orderPriceB' : 'priceB', 'actualPrice', 'discountPrice', edit ? 'orderInfo.orderStateB' : 'ccOrder.orderStatusB',
      'cancelOrder', 'enableProfitShare', 'refundPriceB', 'serviceChargeB', 'cancelTimeB', 'distanceTimeB', 'cancelRemarkB',
    ],
    1: [edit ? 'orderInfo.orderPriceB' : 'priceB', 'actualPrice', 'discountPrice', edit ? 'orderInfo.orderStateB' : 'ccOrder.orderStatusB', 'refundPriceB',
      'cancelRemarkB'],
  };

  useEffect(() => {
    (async () => {
      if (JSON.stringify(order) !== '{}') {
        const refundInfo = order;
        if (edit) {
          const A = refundInfo.orderInfo.suborderId.split('-')[1];
          const discount = await store.getOrderDiscountInfo({ orderId: order.orderInfo.orderId });
          const costAmount = discount.reduce((acc, item) => {
            const { costPrice } = item;
            acc += costPrice;
            return acc;
          }, 0);
          setCostTotalPrice(costAmount);
          const orderInfo = await store.get(order.orderInfo.orderId);
          const { directRoute } = orderInfo?.ccOrder;
          const { price } = orderInfo;
          const { cancelTime, distanceTime, refundPrice, serviceCharge, cancelRemark } = refundInfo;
          const { discountInfos = [], price: orderPrice, originalPrice } = orderInfo;
          const discountPrice = discountInfos.reduce((acc, item) => {
            const { discountPrice: value } = item;
            acc += value;
            return acc;
          }, 0);
          let preferentialCost = 0;
          for (const item of discountInfos) {
            const { cost = 0 } = item;
            preferentialCost += cost;
          }
          _.assign(orderRefund, refundInfo);
          if (A === '1' && !directRoute) {
            setABIndex('0');
            store._orderABRefundStatus = '0';
          } else if (!directRoute) {
            setABIndex('1');
            store._orderABRefundStatus = '1';
            _.set(orderRefund, 'orderInfo.orderPriceB', price);
            _.set(orderRefund, 'orderInfo.orderStateB', refundInfo?.orderInfo?.orderState);
            _.set(orderRefund, 'cancelTimeB', cancelTime);
            _.set(orderRefund, 'distanceTimeB', distanceTime);
            _.set(orderRefund, 'discountPriceB', `${discountPrice.toFixed(2)} / ${preferentialCost.toFixed(2)}`);
            _.set(orderRefund, 'serviceChargeB', serviceCharge);
            _.set(orderRefund, 'cancelRemarkB', cancelRemark);
          }
          setAB(!directRoute);
          initAccount(store._orderABRefundStatus);
          setEnableProfitShare(orderInfo?.enableProfitShare || false);
          setCancelOrder(orderInfo?.ccOrder?.orderStatus === 0);
          _.set(orderRefund, 'cancelOrder', refundInfo?.ccOrder?.orderStatus === 0);
          _.set(orderRefund, 'enableProfitShare', orderInfo?.enableProfitShare || false);
          _.set(orderRefund, 'discountPrice', `${discountPrice.toFixed(2)} / ${preferentialCost.toFixed(2)}`);
          _.set(orderRefund, 'actualPrice', orderPrice?.toFixed(2) || 0);
          _.set(orderRefund, 'orderInfo.orderPrice', originalPrice?.toFixed(2) || 0);
          // eslint-disable-next-line require-atomic-updates
          orderRefund.ccOrder = {
            predictBeginDate: orderInfo.ccOrder.predictBeginDate,
          };
        } else {
          const discount = await store.getOrderDiscountInfo({ orderId: order?.id });
          const costAmount = discount.reduce((acc, item) => {
            const { costPrice } = item;
            acc += costPrice;
            return acc;
          }, 0);
          setCostTotalPrice(costAmount);
          const { directRoute } = refundInfo?.ccOrder;
          const { discountInfos = [], price, originalPrice } = refundInfo;
          const discountPrice = discountInfos.reduce((acc, item) => {
            const { discountPrice: value } = item;
            acc += value;
            return acc;
          }, 0);
          let preferentialCost = 0;
          for (const item of discountInfos) {
            const { cost = 0 } = item;
            preferentialCost += cost;
          }
          const diff = moment.duration(moment(refundInfo.ccOrder.predictBeginDate).diff(moment()));
          const diffStr = `${Math.floor(diff.asHours())}小时${diff.minutes()}分钟`;
          setAB(!directRoute);
          // 获取分账方信息  但是要区分ab段  directRoute  false为a段  true为b
          initAccount(store._orderABRefundStatus);
          setEnableProfitShare(refundInfo?.enableProfitShare || false);
          setCancelOrder(refundInfo?.ccOrder?.orderStatus === 0);
          _.assign(orderRefund, refundInfo);
          _.set(orderRefund, 'cancelOrder', refundInfo?.ccOrder?.orderStatus === 0);
          _.set(orderRefund, 'cancelCoupon', true);
          _.set(orderRefund, 'enableProfitShare', refundInfo?.enableProfitShare || false);
          _.set(orderRefund, 'discountPrice', `${discountPrice.toFixed(2)} / ${preferentialCost.toFixed(2)}`);
          _.set(orderRefund, 'actualPrice', price?.toFixed(2) || 0);
          _.set(orderRefund, 'price', originalPrice?.toFixed(2) || 0);
          _.set(orderRefund, 'cancelTime', moment().format('YYYY-MM-DD HH:mm:ss'));
          _.set(orderRefund, 'distanceTime', diffStr);
          // 赋值给B段
          if (!directRoute) {
            _.set(orderRefund, 'orderInfo.orderPriceB', refundInfo.price);
            _.set(orderRefund, 'priceB', refundInfo.price);
            _.set(orderRefund, 'orderInfo.orderStateB', refundInfo?.orderInfo?.orderStatus);
            _.set(orderRefund, 'ccOrder.orderStatusB', refundInfo?.ccOrder?.orderStatus);
            _.set(orderRefund, 'cancelTimeB', '');
            _.set(orderRefund, 'distanceTimeB', '');
            _.set(orderRefund, 'refundPriceB', '');
            _.set(orderRefund, 'serviceChargeB', '');
            _.set(orderRefund, 'cancelRemarkB', '');
            _.set(orderRefund, 'discountPriceB', `${discountPrice.toFixed(2)} / ${preferentialCost.toFixed(2)}`);
          }
        }
        editCtx.origin = _.cloneDeep(refundInfo);
      }
    })();
    return (() => {
      store._orderABRefundStatus = '0';
    });
  }, []);

  useEffect(() => {
    if (order.type === '2' || toJS(orderRefund)?.ccOrder?.orderStatus == 3) {
      setTabIndex('1');
      store._orderRefundStatus = '1';
    }
  }, [toJS(orderRefund)]);

  const overrideModel = {
    cancelRemark: {
      label: t`申请说明`,
      ui: {
        renderer: (v) => <Input.TextArea value={v} />,
        itemProps: { required: true },
      },
    },
    cancelRemarkB: {
      label: t`申请说明`,
      ui: {
        renderer: (v) => <Input.TextArea value={v} />,
        itemProps: { required: true },
      },
    },
    enableProfitShare: {
      label: t`是否开启分账`,
      ui: {
        renderer: (v) => <Switch disabled={enableProfitShare} checked={v} unCheckedChildren="否" checkedChildren="是" autoWidth />,
      },
    },
    cancelOrder: {
      label: t`是否取消订单`,
      ui: {
        renderer: (v) => <Switch disabled={cancelOrder} checked={v} unCheckedChildren="否" checkedChildren="是" autoWidth />,
      },
    },
    discountPrice: {
      label: t`券面值/第三方价格`,
    },
    discountPriceB: {
      label: t`券面值/第三方价格`,
    },
    refundPrice: {
      label: '退款金额',
      ui: {
        renderer: (v) => (store._orderRefundStatus !== '0' ? <span>{v}</span> : <Input value={v} />),
        itemProps: { required: store._orderRefundStatus === '0' },
      },
    },
  };

  const initAccount = async (type) => {
    const directRoute = type;
    if (edit) {
      const { refundPayers } = order;
      const initAccounts = refundPayers?.map((item) => ({
        ...item,
        pendingSettlementAmount: (item.pendingSettlementAmount / 100).toFixed(2),
        contributionAmount: (item.contributionAmount / 100).toFixed(2),
      }));
      const amountTotal = refundPayers.reduce((acc, item) => {
        const { pendingSettlementAmount, refundedAmount } = item;
        const sum = pendingSettlementAmount - refundedAmount;
        return sum + acc;
      }, 0);
      setRefundAmount(amountTotal / 100);
      setRefundAmountB(amountTotal / 100);
      store.initAccountsA = initAccounts;
      store.initAccountsB = initAccounts;
      store.accounts = refundPayers;
      store.accountB = refundPayers;
      setAccountsA(initAccounts);
      setAccountsB(initAccounts);
    } else {
      const { id } = order;
      const A = await store.getAccount(id, false);
      const { extras } = await store.getDictItem('offlinePay', 'company');
      // 初始化分账金额
      const initAccountsA = A?.map((item) => ({
        ...item,
        pendingSettlementAmount: ((item.pendingSettlementAmount - item.refundedAmount) / 100).toFixed(2),
        contributionAmount: ((item.pendingSettlementAmount - item.refundedAmount) / 100).toFixed(2),
      }));
      // 计算分账方已经退款多少
      const amountTotal = A.reduce((acc, item) => {
        const { pendingSettlementAmount, refundedAmount } = item;
        const sum = pendingSettlementAmount - refundedAmount;
        return sum + acc;
      }, 0);
      setAccountSupplement(initAccountsA);
      if (!initAccountsA.some((p) => p.targetId === extras['兜底公司']?.value || p.targetId === 'PLATFORM')) {
        const _supplement = [...initAccountsA, { targetName: t`平台`, targetId: 'PLATFORM', targetType: 'PLATFORM', pendingSettlementAmount: 0, contributionAmount: 0 }];
        setAccountSupplement(_supplement);
      }
      setRefundAmount(amountTotal / 100);
      store.initAccountsA = initAccountsA;
      store.accounts = A;
      setAccountsA(initAccountsA);
      // 如果是换成线路
      if (directRoute) {
        const B = await store.getAccount(id, true);
        // 初始化分账金额
        const initAccountB = B?.map((item) => ({
          ...item,
          pendingSettlementAmount: ((item.pendingSettlementAmount - item.refundedAmount) / 100).toFixed(2),
          contributionAmount: ((item.pendingSettlementAmount - item.refundedAmount) / 100).toFixed(2),
        }));
        const amountTotalB = B.reduce((acc, item) => {
          const { pendingSettlementAmount, refundedAmount } = item;
          const sum = pendingSettlementAmount - refundedAmount;
          return sum + acc;
        }, 0);
        setRefundAmountB(amountTotalB / 100);
        store.accountB = B;
        store.initAccountsB = initAccountB;
        setAccountsB(initAccountB);
      }
    }
  };

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(orderRefund, name, value);

    if (name === 'cancelTime') {
      const diff = moment.duration(moment(orderRefund.ccOrder.predictBeginDate).diff(moment(value)));
      const diffStr = `${Math.floor(diff.asHours())}小时${diff.minutes()}分钟`;
      _.assign(orderRefund, { distanceTime: diffStr });
    }

    if (name === 'cancelTimeB') {
      const diff = moment.duration(moment(orderRefund.ccOrder.predictBeginDate).diff(moment(value)));
      const diffStr = `${Math.floor(diff.asHours())}小时${diff.minutes()}分钟`;
      _.set(orderRefund, 'distanceTimeB', diffStr);
    }

    if (name === 'refundPrice') {
      const diffPrice = costTotalPrice - Number(value);
      _.assign(orderRefund, { serviceCharge: diffPrice.toFixed(2) });
    }

    if (name === 'refundPriceB') {
      const diff = refundAmountB - Number(value);
      _.assign(orderRefund, { serviceChargeB: diff.toFixed(2) });
    }

    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign, no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    const { _orderRefundStatus, _orderABRefundStatus, initAccountsA, initAccountsB, accounts } = store;
    if (_orderRefundStatus === '1' && orderRefund.refundPrice === '0') {
      return refundCaution();
    }
    let verifyPrice;
    let verifyInitAccount;
    if (AB && _orderABRefundStatus !== '1' && _orderRefundStatus !== '1') {
      verifyPrice = verifyAccount(AB, initAccountsA, toJS(orderRefund));
      verifyInitAccount = verifyAccountTotal(false, store.accounts, initAccountsA);
      verifyPrice = verifyAccount(AB, initAccountsB, toJS(orderRefund));
      verifyInitAccount = verifyAccountTotal(false, store.accountB, initAccountsB);
    } else if (_orderABRefundStatus !== '1' && _orderRefundStatus !== '1') {
      verifyPrice = verifyAccount(AB, initAccountsA, toJS(orderRefund));
      verifyInitAccount = verifyAccountTotal(false, store.accounts, initAccountsA);
    }
    if (verifyPrice || verifyInitAccount) {
      return;
    }
    let type = Number(_orderRefundStatus) + 1;
    if (orderRefund.ccOrder.orderStatus === 3) {
      type = 2;
    }
    const { serviceCharge, refundPrice } = toJS(orderRefund);
    // 订单总额不可大于退款金额  在其他退款内
    if (serviceCharge < 0) {
      return Notification.open({
        title: '警告⚠️',
        content:
          '退款总和不可大于订单价格',
        type: 'warning',
      });
    }
    const prices = computePrice({ order: orderRefund, refundPrice: Number(refundPrice) });
    const { otherPrice, platformPrice } = prices;
    if (_orderRefundStatus === '0') {
      Dialog.confirm({
        title: t`退款是否提交财务`,
        content: (<div>
          {(platformPrice !== null) && <span>{t`平台退款: ${platformPrice.toFixed(2)} 元`}</span>}
          <br />
          {(otherPrice !== null) && <span>{t`第三方退款: ${otherPrice.toFixed(2)} 元`}</span>}
        </div>),
        onOk: () => onSubmit?.(orderRefund, '2', type, accountsA, accountsB, AB, enableProfitShare, accounts),
        onCancel: () => onSubmit?.(orderRefund, '1', type, accountsA, accountsB, AB, enableProfitShare, accounts),
        okProps: {
          children: '是', // 设置确定按钮的文本
        },
        cancelProps: {
          children: '否', // 设置取消按钮的文本
        },
      });
    } else {
      if (!accountSupplement.some((p) => p.check)) {
        Message.error({ content: t`请选择分账方` });
        return;
      }
      Dialog.confirm({
        title: t`退款是否提交财务`,
        content: (<div>
          {(platformPrice !== null) && <span>{t`平台退款: ${platformPrice.toFixed(2)} 元`}</span>}
          <br />
          {(otherPrice !== null) && <span>{t`第三方退款: ${otherPrice.toFixed(2)} 元`}</span>}
        </div>),
        onOk: () => onSubmit?.(orderRefund, '2', type, accountsA, accountsB, AB, enableProfitShare, accounts, accountSupplement),
        okProps: {
          children: '是', // 设置确定按钮的文本
        },
      });
    }
  };

  // 编辑
  const handleOnEdit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    const { _orderRefundStatus, _orderABRefundStatus, initAccountsA, initAccountsB, accounts } = store;
    const { serviceCharge, refundPrice, refundPriceB } = toJS(orderRefund);
    if (_orderRefundStatus === '1' && orderRefund.refundPrice === '0') return refundCaution();
    let verifyPrice;
    let verifyInitAccount;
    if (AB) {
      if (_orderABRefundStatus === '0') {
        if (refundPrice === '0' || refundPrice === undefined) {
          return isRefundPrice();
        }
        verifyPrice = verifyAccount(false, initAccountsA, toJS(orderRefund));
        verifyInitAccount = verifyAccountTotal(true, store.accounts, initAccountsA);
      } else {
        if (refundPriceB === '0' || refundPriceB === undefined) {
          return isRefundPrice();
        }
        verifyPrice = verifyAccount(true, initAccountsB, toJS(orderRefund));
        verifyInitAccount = verifyAccountTotal(true, store.accounts, initAccountsB);
      }
    } else {
      if (refundPrice === '0' || refundPrice === undefined) {
        return isRefundPrice();
      }
      verifyPrice = verifyAccount(false, initAccountsA, toJS(orderRefund));
      verifyInitAccount = verifyAccountTotal(true, store.accounts, initAccountsA);
    }
    if (verifyPrice || verifyInitAccount) return;
    // 订单总额不可大于退款金额  在其他退款内
    if (serviceCharge < 0) {
      return Notification.open({
        title: '警告⚠️',
        content:
          '退款总和不可大于订单价格',
        type: 'warning',
      });
    }
    const prices = computePrice(orderRefund);
    const { otherPrice, platformPrice } = prices;
    Dialog.confirm({
      title: t`退款是否提交财务`,
      content: (<div>
        {(platformPrice !== null) && <span>{t`平台退款: ${Number(platformPrice).toFixed(2)} 元`}</span>}
        <br />
        {(otherPrice !== null) && <span>{t`第三方退款: ${Number(otherPrice).toFixed(2)} 元`}</span>}
      </div>),
      onOk: () => onEdit?.(orderRefund, _orderRefundStatus, _orderABRefundStatus, accountsA, accountsB, enableProfitShare, accounts),
    });
  };

  /**
   * tab事件回调  是否允许切换tab
   * @param {*} v
   */
  const handleTabChange = (v) => {
    if (!edit && orderRefund?.ccOrder?.orderStatus !== 3) {
      store._orderRefundStatus = v;
      store._orderABRefundStatus = '0';
    }
  };

  /**
   * AB段 tab事件回调  是否允许切换tab
   * @param {*} v
   */
  const handleABTabChange = (v) => {
    if (!edit && orderRefund?.ccOrder?.orderStatus !== 3) {
      store.orderABRefundStatus = v;
    }
  };

  /**
   * 分账方输入分账金额事件
   * @param {*} e
   * @param {*} r
   * @param {*} i
   */
  const handleAccountPrice = (e, r, i, type) => {
    if (currentEditAccount(enableProfitShare)) return;
    if (type === 'A') {
      // 修改前校验是否修改过 出资金额
      if (currentIsEdit(accountsA)) return;
      setAccountsA((pre) => {
        const res = [...pre];
        res[i].pendingSettlementAmount = e;
        return res;
      });
    } else {
      if (currentIsEdit(accountsB)) return;
      setAccountsB((pre) => {
        const res = [...pre];
        res[i].pendingSettlementAmount = e;
        return res;
      });
    }
  };

  /**
   * 分账方输入退款金额事件
   * @param {*} e
   * @param {*} r
   * @param {*} i
   */
  const handleRefundPrice = (e, r, i, type) => {
    if (type === 'A') {
      if (currentIsEditPS(store.accounts, accountsA)) return;
      setAccountsA((pre) => {
        const res = [...pre];
        res[i].contributionAmount = e;
        return res;
      });
    } else {
      if (currentIsEditPS(store.accountB, accountsB)) return;
      setAccountsB((pre) => {
        const res = [...pre];
        res[i].contributionAmount = e;
        return res;
      });
    }
  };

  /**
* 是否由平台代付
* @param {*} e
* @param {*} i
* @param {*} platType 区分退票和其他
*/
  const handleAccountPlat = (e, i, v, platType) => {
    if (platType === 'A') {
      setAccountsA((pre) => {
        const res = [...pre];
        res[i].platformContribution = e;
        return res;
      });
    } else {
      setAccountsB((pre) => {
        const res = [...pre];
        res[i].platformContribution = e;
        return res;
      });
    }
  };

  const handleSupplementCheck = (e, i) => {
    const temp = _.cloneDeep(accountSupplement);
    temp[i].check = e;
    setAccountSupplement(temp);
    calculateRefundPrice(temp);
  };

  const handleChangeAmountSp = (e, r, i) => {
    const temp = _.cloneDeep(accountSupplement);
    const value = e || 0;
    temp[i].contributionAmount = value;
    setAccountSupplement(temp);
    calculateRefundPrice(temp);
  };

  function calculateRefundPrice(data) {
    const temp = _.cloneDeep(data);
    let price = 0;
    for (let i = 0; i < temp.length; i++) {
      const { contributionAmount = 0, check = null } = temp[i];
      if (check) {
        price += Number(contributionAmount);
      }
    }
    _.set(orderRefund, 'refundPrice', price.toFixed(2));
  }

  return (
    <Form
      inline
      value={orderRefund}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <Tab
        // eslint-disable-next-line no-nested-ternary
        activeKey={edit ? tabIndex : (orderRefund?.ccOrder?.orderStatus == 3 ? '1' : store._orderRefundStatus)}
        onChange={(v) => handleTabChange(v)}
      >
        {tabItems.map((item) => (<Tab.Item key={item.key} title={item.label} />))}
      </Tab>
      {/* ad段 */}
      {
        AB &&
        <Tab
          // eslint-disable-next-line no-nested-ternary
          activeKey={edit ? abIndex : store._orderABRefundStatus}
          onChange={(v) => handleABTabChange(v)}
        >
          {abTabItems.map((item) => (<Tab.Item key={item.key} title={item.label} />))}
        </Tab>
      }
      {(store._orderRefundStatus === '0' && store._orderABRefundStatus === '0' && AB) && <TitleGrid title={t`A段退款信息`} />}
      {(store._orderRefundStatus === '0' && store._orderABRefundStatus === '1' && AB) && <TitleGrid title={t`B段退款信息`} />}
      {(store._orderRefundStatus === '1' || !AB) && <TitleGrid title={t`退款信息`} />}
      {(store._orderABRefundStatus === '0') && <FieldsGrid
        formData={orderRefund}
        mode={modal[0]}
        overrideModel={overrideModel}
        columns={4}
        // eslint-disable-next-line no-nested-ternary
        fields={tabContentA[isEdit === 1 ? tabIndex : (orderRefund?.ccOrder?.orderStatus == 3 ? '1' : store._orderRefundStatus)]}
      />}
      {store._orderABRefundStatus === '1' && <FieldsGrid
        formData={orderRefund}
        mode={modal[0]}
        overrideModel={overrideModel}
        columns={store._orderRefundStatus === '0' ? 4 : 3}
        // eslint-disable-next-line no-nested-ternary
        fields={tabContentB[isEdit === 1 ? tabIndex : (orderRefund?.ccOrder?.orderStatus == 3 ? '1' : store._orderRefundStatus)]}
      />}
      {(store._orderRefundStatus === '0' && store._orderABRefundStatus === '0' && AB) && <TitleGrid title={t`A段分账方信息`} />}
      {(store._orderRefundStatus === '0' && store._orderABRefundStatus === '1' && AB) && <TitleGrid title={t`B段分账方信息`} />}
      {!AB && <TitleGrid title={t`分账方信息`} />}
      {(store._orderRefundStatus === '0' && store._orderABRefundStatus === '0') && <TauTable
        instanceId={tableId}
        tableLayout="fixed"
        hidePagination
        style={{ width: '100%' }}
        dataSource={accountsA}
        rowKey="account" // 设置每行的唯一标识
        columns={[
          { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.ticIdx(i) },
          column('targetName', { width: 100 }),
          column('pendingSettlementAmount', {
            width: 88,
            cell: (v, i, r) => (
              <>
                <NumberPicker value={v} precision={2} style={{ width: 80 }} onChange={(e) => handleAccountPrice(e, r, i, 'A')} />
              </>
            ),
          }),
          column('contributionAmount', {
            width: 88,
            cell: (v, i, r) => (
              <>
                <NumberPicker value={v} precision={2} style={{ width: 80 }} onChange={(e) => handleRefundPrice(e, r, i, 'A')} />
              </>
            ),
          }),
          {
            title: t`平台代付`,
            dataIndex: 'platformContribution',
            width: 50,
            cell: (text, i, refund) => (
              <Checkbox checked={text} disabled={!refund.settled} onChange={(e) => handleAccountPlat(e, i, refund, 'A')} />),
          },
        ]}
      />}
      {(store._orderRefundStatus === '0' && store._orderABRefundStatus === '1') && <TauTable
        instanceId={tableId}
        tableLayout="fixed"
        hidePagination
        style={{ width: '100%' }}
        dataSource={accountsB}
        rowKey="account" // 设置每行的唯一标识
        columns={[
          { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.ticIdx(i) },
          column('targetName', { width: 100 }),
          column('pendingSettlementAmount', {
            width: 88,
            cell: (v, i, r) => (
              <>
                <Input value={v} style={{ width: 80 }} onChange={(e) => handleAccountPrice(e, r, i, 'B')} />
              </>
            ),
          }),
          column('contributionAmount', {
            width: 88,
            cell: (v, i, r) => (
              <>
                <Input value={v} style={{ width: 80 }} onChange={(e) => handleRefundPrice(e, r, i, 'B')} />
              </>
            ),
          }),
          {
            title: t`平台代付`,
            dataIndex: 'platformContribution',
            width: 50,
            cell: (text, i, refund) => (
              <Checkbox checked={text} disabled={!refund.settled} onChange={(e) => handleAccountPlat(e, i, refund, 'B')} />),
          },
        ]}
      />}

      {(store._orderRefundStatus === '1' && !AB) && <TauTable
        instanceId={tableId}
        tableLayout="fixed"
        hidePagination
        style={{ width: '100%' }}
        dataSource={accountSupplement}
        rowKey="account" // 设置每行的唯一标识
        columns={[
          { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.ticIdx(i) },
          column('targetName', {
            width: 100,
            cell: (v, i, r) => {
              const { targetName, targetId } = r || {};
              return (
                <>
                  <div>{targetName}</div>
                  <div style={{ color: '#999' }}>{targetId}</div>
                </>
              );
            },
          }),
          column('pendingSettlementAmount', {
            width: 88,
          }),
          column('contributionAmount', {
            width: 88,
            cell: (v, i, r) => (r.check ? (
              <NumberPicker value={v} precision={2} style={{ width: 80 }} onChange={(e) => handleChangeAmountSp(e, r, i)} />
            ) : <>{v}</>),
          }),
          {
            title: t`选择`,
            dataIndex: 'check',
            width: 50,
            cell: (text, i, refund) => (
              <Checkbox checked={text} onChange={(e) => handleSupplementCheck(e, i, refund)} />),
          },
        ]}
      />}

      {
        store._orderRefundStatus === '0' &&
        <RefundRule />
      }

      <AttachmentPanel refund={orderRefund} mode={modal[0]} />

      <DrawerFooter>
        <FromItem>
          <Form.Submit validate type="primary" onClick={edit ? handleOnEdit : handleSubmit}>{edit ? t`修改` : t`保存`}</Form.Submit>
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
}

const AttachmentPanel = observer(({ refund, mode }) => {
  const [curAttachment, setCurAttachment] = useState();
  const [idx, setIdx] = useState(-1); // 当前选中的附件
  const isViewMode = mode === 'check';

  useEffect(() => {
    if (refund?.attachments?.length) setIdx(0);
  }, [refund?.attachments]);

  const handleAddAttachment = () => {
    if (!refund?.attachments) refund.attachments = [];
    refund.attachments.push({ title: t`附件`, description: t`附件说明`, binaryId: [] });
    setIdx(refund.attachments.length - 1);
  };

  const handleDeleteAttachment = (i, e) => {
    refund.attachments.splice(i, 1);
    if (i === idx) setIdx(i - 1);
    e.preventDefault();
    e.stopPropagation();
  };

  return (
    <>
      <TitleGrid title={<span>{t`附件`}{mode !== 'view' && <Button type="primary" style={{ marginLeft: 24 }} onClick={handleAddAttachment} >{t`添加附件`}</Button>}</span>} />
      <ResponsiveGrid gap={[0, 30]} style={{ paddingLeft: 20 }}>
        <Cell colSpan={12}>
          <TauTable
            primaryKey="orderNumber"
            size="small"
            hidePagination
            tableLayout="fixed"
            dataSource={toJS(refund?.attachments)}
            cellProps={(r) => ({ style: { cursor: 'pointer', backgroundColor: idx === r ? 'var(--color-fill1-1)' : 'unset' } })}
            columns={[
              { title: '#', dataIndex: 'idx', width: 44, cell: (_, i) => i + 1 },
              column('title', {}, orderModel?.attachments[0]),
              column('description', {}, orderModel?.attachments[0]),
              { title: t`附件个数`, dataIndex: 'cnt', width: 84, cell: (_, i, row) => <Button type="primary" text>{row.binaryId?.length}</Button> },
            ].concat(isViewMode ? [{ align: 'left', width: 30, cell: (_, i) => (i === idx && <Icon type="arrow-right" size="xs" style={{ color: 'var(--color-line1-4)' }} />) }] : [
              {
                title: <span style={{ paddingLeft: 16 }}>{t`操作`}</span>,
                dataIndex: 'title',
                align: 'left',
                width: 110,
                cell: (_, i, row) => (
                  <span>
                    <Button type="primary" text onClick={() => setCurAttachment(row)} >{t`编辑`}</Button>
                    <span>  </span>
                    <Button type="primary" text onClick={(e) => handleDeleteAttachment(i, e)} >{t`删除`}</Button>
                    {i === idx && <Icon type="arrow-right" size="xs" style={{ marginLeft: 16, color: 'var(--color-line1-4)' }} />}
                  </span>
                ),
              },
            ])}
            onRowClick={(_, index) => setIdx(index)}
          />
        </Cell>
        <Cell colSpan={5} style={{ paddingTop: 30 }}>
          {idx >= 0 && <UploadPanel
            isPreview={isViewMode}
            prefix={`partner:${refund.id}:attachment`}
            binaryIds={idx === -1 ? [] : toJS(refund.attachments[idx]?.binaryId)}
            onUploaded={(meta) => {
              refund.attachments[idx]?.binaryId.push(meta.binaryId);
            }}
            onRemove={(info) => {
              refund.attachments[idx]?.binaryId.splice(refund.attachments[idx]?.binaryId.findIndex((r) => r == info.uid), 1);
            }}
          />}
        </Cell>
      </ResponsiveGrid>
      <Dialog
        visible={!!curAttachment}
        onCancel={() => setCurAttachment(false)}
        onClose={() => setCurAttachment(false)}
        title={t`附件`}
        style={{ width: '50%' }}
        footer={null}
      >
        <AttachmentForm
          data={curAttachment}
          onSubmit={(data) => {
            _.assign(refund.attachments[idx], data);
            setCurAttachment(false);
          }}
          onCancel={() => setCurAttachment(false)}
        />
      </Dialog>
    </>
  );
});

export default observer(OrderRefund);

